<template>
  <div style="height:100%">
    <!-- 搜索栏 -->
    <div class="head">
      <el-tag style="height: 40px;font-size: 16px;line-height: 40px">技术人员表</el-tag>
      <div>
  <el-input
    placeholder="请输入关键字"
    suffix-icon="el-icon-search"
    v-model="input"
    style="width: 220px"> 
  </el-input>
  <el-button type="primary" icon="el-icon-plus" @click="adds">添加</el-button>
  </div>
    </div>
    
  
    <!-- 点击添加按钮的弹出框 -->
    <el-dialog :title='add? "添加技术人员": "修改技术人员"' :visible.sync="dialogFormVisible">
      <div class="Dividing" style="margin-bottom:2%"></div>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="工号" prop="Number"  :label-width="formLabelWidth">
          <el-input v-model="form.Number" clearable></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="Password"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.Password" show-password ></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.contact" clearable></el-input>
        </el-form-item>
        <el-form-item label="微信号" prop="wechat"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.wechat" clearable></el-input>
        </el-form-item>
        <el-form-item label="QQ号" prop="QQ"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.QQ" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks"  :label-width="formLabelWidth" style="margin-top:20px">
          <el-input v-model="form.remarks" clearable></el-input>
        </el-form-item>
         <el-form-item label="角色" prop="Role" :label-width="formLabelWidth" style="margin-top:20px">
      <el-select v-model="form.Role" placeholder="请选择角色权限">
        <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
    </el-option>
      </el-select>
      
    </el-form-item>
     </el-form>
         <div slot="footer" class="dialog-footer" v-if="add">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm ('form')">添 加</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit('form')">修 改</el-button>
      </div>
     
    </el-dialog>

    <!-- 表格 -->
      <el-table :data="searchMan.slice((currentPage-1)*pagesize,currentPage*pagesize)" 
    height="70%"
    stripe
    style="width: 100%;padding: 20px 20px;">

    <el-table-column type="expand">
      <template slot-scope="props">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-form-item label="工号:">
            <span>{{ props.row.Number}}</span>
          </el-form-item>
          <el-form-item label="姓名:">
            <span>{{ props.row.name}}</span>
          </el-form-item>
          <el-form-item label="密码:">
            <span>{{ props.row.Password}}</span>
          </el-form-item>
          <el-form-item label="角色:">
            <span>{{ props.row.Role}}</span>
          </el-form-item>
        </el-form>
      </template>
    </el-table-column>

        <el-table-column label="序号" width="50" align="center">
<template  slot-scope="scope"><span>{{scope.$index+(currentPage - 1) * pagesize + 1}} </span></template>
</el-table-column>

        <el-table-column prop="Number" label="工号" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="name" label="姓名" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="Password" label="密码" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="contact" label="联系方式" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="wechat" label="微信号" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="QQ" label="QQ号" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="remarks" label="备注" :label-width="formLabelWidth"></el-table-column>
        <el-table-column prop="Role" label="角色" :label-width="formLabelWidth"></el-table-column>
        <el-table-column label="操作" :label-width="formLabelWidth">
          <template slot-scope="scope">
            <el-button
               @click.native.prevent="detail(scope.$index, scope.row)"
              type="text"
              size="small"
            >编辑</el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.row)"
              type="text"
              size="small"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    <!-- 分页符 -->
    <div>
        <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page=currentPage
      :page-sizes="[10]"
      :page-size=pagesize
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.searchMan.length"
      style="margin-top: 20px;float: right">
    </el-pagination>
    </div>


  </div>
</template>


<script>
// 表格
import { getAdmins, addAdmin, removeAdmin,isInteger,updateAdmin } from '@/api/Technology'
export default {
    data() {
    return {
      options: [{
        value: 'admin',
        label: '管理员'
      }, {
        value: 'user',
        label: '录入员'
      }, {
        value: 'Developer',
        label: '开发者'
      }, {
        value: 'Leader',
        label: '检查员'
      }], // 筛选角色数据
      pagesize: 10, // 分页每页数据数
      currentPage: 1, // 当前页数
      input:'',//输入框内容
      value: '',
      list:"",
        rules: {
        Number: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          {validator:isInteger,trigger:"blur",message: '请输入数字'}
          ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' },
        ],
        contact: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          {validator:isInteger,trigger:"blur",message: '请输入数字'}
        ],
         Password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {validator:isInteger,trigger:"blur",message: '请输入数字'}
        ],
        wechat: [
          { required: true, message: '请输入微信号', trigger: 'blur' },
          {validator:isInteger,trigger:"blur",message: '请输入数字'}
        ],
        QQ: [
          { required: true, message: '请输入QQ号', trigger: 'blur' },
          {validator:isInteger,trigger:"blur",message: '请输入数字'}
        ],
        remarks: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ],
        Role:[
           { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      }, // 表单验证规则
      // 添加数据的数组
      dialogFormVisible: false,
      search:false,
      form: {},
      input: '',
      num:0,
      formLabelWidth: "150px",
      add: false,
    };
  },
   mounted () {
    this.getdata()
  },
  watch:{
    searchMan(val){
      this.total = val.length
    }
  },
    computed: {
    searchMan () {
      var value = this.input
      var select = this.value
      if (value && select) {
        var list = this.list.filter(data => {
          return Object.keys(data).some(key => {
            return String(data[key]).toLowerCase().match(value)
          })
        })
        return list.filter(item => {
          return item.Admin === select
        })
      }
      if (value) {
        return this.list.filter(data => {
          return Object.keys(data).some(key => {
            return String(data[key]).toLowerCase().match(value)
          })
        })
      } else if (select) {
        return this.list.filter(item => {
          return item.Admin === select
        })
      }
      return this.list
    }
  },
  methods: {
       handleSizeChange (size) {
      this.pagesize = size
    },
    submitForm (form) {
this.$refs[form].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将上传此用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var test = /\s*/g
            let query = {
              Number: this.form.Number.replace(test, ''),
              name: this.form.name.replace(test, ''),
              Password: this.form.Password.replace(test, ''),
              contact: this.form.contact.replace(test, ''),
              remarks: this.form.remarks.replace(test, ''),
              QQ: this.form.QQ.replace(test, ''),
              wechat: this.form.wechat.replace(test, ''),
              Role: this.form.Role.replace(test, ''),
            }
           console.log(query)
            let add = async () => { 
              try {
                await addAdmin(query)
              } catch (err) {
                console.log(err)
              }
            }
            add()
            this.list.push(query)
            // this.list = this.data
            this.form = {}
            this.$message({
              type: 'success',
              message: '上传成功!'
            })
            this.dialogFormVisible = false
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消上传'
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
        getdata () {
      let data = async () => {
        try {
          let result = await getAdmins()
          if (result) {
            this.list = result
            this.loading=false
          }
        } catch (err) {
          console.log(err)
        }
      }
      data()
      
    },
      handleCurrentChange (currentPage) {
      this.currentPage = currentPage
    },
    deleteRow(row) {
       for(var i = 0;i<this.list.length;i++){
        if(this.list[i].Role=="admin"){
         this.num = parseInt(this.num) +parseInt("1")
         console.log(this.num)
        }
      }
      if(this.num==1&&row.Role=="admin"){
        this.$confirm('该用户为最后一个管理员，确定删除吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       this.$confirm('删除后需自己前往数据库添加管理员，否则无法管理用户，请再一次确认', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let remove = async () => {
          try {
            await removeAdmin(row.AdminId)
          } catch (err) {
            console.log(err)
          }
        } 
        remove()
        let index = this.list.findIndex(item => {
          return item === row
        })
        this.list.splice(index, 1)
        // this.list = this.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.dialogFormVisible = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
        this.num=0
      }else{
       this.$confirm('此操作将删此用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let remove = async () => {
          try {
            await removeAdmin(row.AdminId)
          } catch (err) {
            console.log(err)
          }
        } 
        remove()
        let index = this.list.findIndex(item => {
          return item === row
        })
        this.list.splice(index, 1)
        // this.list = this.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.dialogFormVisible = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      this.num=0
      }
    },
     adds() {
      this.dialogFormVisible = true;
      this.form = {};
      this.add = true;
    },
    detail(index, item) {
      this.dialogFormVisible = true;
      this.form = item;
      this.add = false;
      // console.log(index, item);
    },
    edit(item) {
    console.log(item)
      this.$confirm("是否修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async() => {
          this.dialogFormVisible = false;
          let res = await updateAdmin(this.form)
          this.$message({
            type: "success",
            message: "修改成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改"
          });
        });
    },


  },

};
</script>


<style>
.head {
    height: 40px;
    margin-bottom: 20px;
    padding: 20px;
    display: flex;
    justify-content: space-between;
}
el-table el-table-column{
  height: 20px;
}
.demo-table-expand{
  font-size: 0px;


}
.el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%  
}

</style>
